import java.util.Arrays;
import java.util.Observable;
import java.util.Observer;
import java.util.Set;
import java.util.TreeSet;

import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.graphics.FontData;
import org.eclipse.swt.widgets.Display;

public class FontContentProvider implements IStructuredContentProvider, Observer {
    private Set<FontItem> fontItems;

    public FontContentProvider() {
        FontData[] scalableFontList = Display.getCurrent().getFontList(
            null, true);
        FontData[] nonScalableFontList = Display.getCurrent().getFontList(
            null, false);

        // Bin for all fonts (ordered by name then style)
        Set<FontData> installedFonts = new TreeSet<FontData>(new FontComparator());

        // Fill font-bin
        installedFonts.addAll(Arrays.asList(scalableFontList));
        installedFonts.addAll(Arrays.asList(nonScalableFontList));
        
        fontItems = new TreeSet<FontItem>();

        for (FontData fontData : installedFonts) {
            if (fontData.getStyle() == 0) {
                // Only add plain fonts
                fontItems.add(new FontItem(fontData, true));
            }
        }
    }

    public Object[] getElements(Object root) {
        return fontItems.toArray();
    }

    public void update(Observable o, Object arg) {
        FontItem fontItem = (FontItem) arg;
        
        for (FontItem fi : fontItems) {
            if (fontItem.getFontData().equals(fi.getFontData())) {
                fontItem.setInstalled(true);
                
                return;
            }
        }
        
        if (fontItem.getFontData().getStyle() == 0) {
            fontItems.add(fontItem);
        }
    }

    public void dispose() {
        fontItems.clear();
    }

    public void inputChanged(Viewer arg0, Object arg1, Object arg2) {
        
    }
}
